package com.tools.payhelper;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;

import com.tools.payhelper.nxes.NXESHook;
import com.tools.payhelper.utils.LogUtil;
import com.tools.payhelper.utils.PayHelperUtils;

import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

/**
 * @author SuXiaoliang
 * @ClassName: Main
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2018年6月23日 下午1:26:26
 */
public class Main implements IXposedHookLoadPackage {
    public static String QQ_PACKAGE = "com.tencent.mobileqq";
    public static String LONGPAY_PACKAGE = "com.ccb.imerchant";
    public static String NXES_PACKAGE = "com.buybal.buybalpay.nxy";
    public static boolean NXES_PACKAGE_ISHOOK = false;
    public static boolean CITTC_PACKAGE_ISHOOK = false;

    private static final String YST_PACKAGE = "com.ysepay.mobileportal.activity";

    public static final String TAG = "PayHelper";

    public static final String PACKAGENAME = "com.buybal.buybalpay.nxy";


    @Override
    public void handleLoadPackage(final XC_LoadPackage.LoadPackageParam lpparam)
            throws Throwable {
        XposedBridge.log("------>handleLoadPackage：" + lpparam.packageName);
        if (!lpparam.packageName.equals(LONGPAY_PACKAGE)) {
            if (lpparam.appInfo == null || (lpparam.appInfo.flags & (ApplicationInfo.FLAG_SYSTEM |
                    ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0) {
                return;
            }
        }
        final String packageName = lpparam.packageName;
        final String processName = lpparam.processName;
        LogUtil.printLog(TAG,
                " pay helper handleLoadPackage:" + packageName);

        try {

            XposedBridge.hookAllMethods(ClassLoader.class, "loadClass", new XC_MethodHook() {
                @Override
                protected void afterHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable {
                    super.afterHookedMethod(param);
                    if (param.hasThrowable()) {
                        return;
                    }
                    if (param.args.length != 1) {
                        return;
                    }


                    Class<?> cls = (Class<?>) param.getResult();
                    String name = cls.getName();

                    if ("s.h.e.l.l.S".equals(name)) {
                        LogUtil.printLog("s.h.e.l.l.S-------hooked");
                        XposedHelpers.findAndHookMethod("s.h.e.l.l.S", (ClassLoader) param.thisObject, "attachBaseContext",
                                Context.class,
                                new XC_MethodHook() {
                                    @Override
                                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                                        super.afterHookedMethod(param);
                                        LogUtil.printLog("afterHookedMethod s.h.l.l.S.attachBaseContext ...");
                                        Context context = (Context) param.args[0];
                                        ClassLoader appClassLoader = context.getClassLoader();
                                        LogUtil.printLog("--->processName:" + processName + " isHooked :" + CITTC_PACKAGE_ISHOOK);
                                        if (NXES_PACKAGE.equals(processName) && !NXES_PACKAGE_ISHOOK) {
                                            NXES_PACKAGE_ISHOOK = true;
                                            NXReceived nxReceived = new NXReceived();
                                            IntentFilter intentFilter = new IntentFilter();
                                            intentFilter.addAction("com.payhelper.nongxingyisao.start");
                                            intentFilter.addAction("com.payhelper.nongxingyisao.search");
                                            context.registerReceiver(nxReceived, intentFilter);

                                            PayHelperUtils.sendmsg(context, "农信易扫hook成功，当前农信易扫版本:" + PayHelperUtils.getVerName(context));
                                            new NXESHook().hook(appClassLoader, context);

                                        }


                                    }
                                }

                        );
                    }
                }
            });
        } catch (Throwable e) {
            XposedBridge.log(e);
        }
    }


    class NXReceived extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtil.printLog("启动NXActivity" + intent.getAction().equals("com.payhelper.nongxingyisao.search"));
            if (intent.getAction().equals("com.payhelper.nongxingyisao.search")) {
                LogUtil.printLog("收到广播查询");
                try {
                    NXESHook.startListResbonse();
                } catch (Exception e) {
                    LogUtil.printLog("#####", "ReceiverNxys 异常" + e.getMessage());
                }
            } else {
                try {
                    Intent intent2 = new Intent(context, XposedHelpers.findClass("com.buybal.buybalpay.activity.ReciveAmtActivity", context.getClassLoader()));
                    intent2.putExtra("type", intent.getStringExtra("type"));
                    intent2.putExtra("apiorder_id", intent.getStringExtra("apiorder_id"));
                    intent2.putExtra("money", intent.getStringExtra("money"));
                    intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent2);

                } catch (Exception e) {
                    PayHelperUtils.sendmsg(context, "NXReceived 异常" + e.getMessage());
                }
            }

        }
    }

    public static String quanfutongPayWay = "";
    public static String quanfutongMoney = "";
    public static String quanfutongApiId = "";

    class QuanfutongReceived extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            XposedBridge.log("生成全付通二维码...");
            try {

                quanfutongMoney = intent.getStringExtra("money");
                quanfutongApiId = intent.getStringExtra("apiorder_id");
                quanfutongPayWay = intent.getStringExtra("type");
                String payWay = "1";
                if (quanfutongPayWay.equals("wechat")) {
                    payWay = "1";
                } else if (quanfutongPayWay.equals("alipay")) {
                    payWay = "2";
                } else if (quanfutongPayWay.equals("qq")) {
                    payWay = "4";
                } else if (quanfutongPayWay.equals("unionpay")) {
                    payWay = "5";
                }

                Class<?> orderManagerCls = XposedHelpers.findClass("cn.swiftpass.enterprise.bussiness.logica.order.OrderManager", context.getClassLoader());
                Class<?> UINotifyListenerCls = XposedHelpers.findClass(" cn.swiftpass.enterprise.bussiness.logica.threading.UINotifyListener", context.getClassLoader());
                Object instance = XposedHelpers.callStaticMethod(orderManagerCls, "getInstance");
                Object UINotifyListener = XposedHelpers.newInstance(UINotifyListenerCls);
                XposedHelpers.callMethod(instance, "unifiedNativePay", quanfutongMoney, payWay, 0, null, null, UINotifyListener);

            } catch (Exception e) {
                PayHelperUtils.sendmsg(context, "QuanfutongReceived 异常" + e.getMessage());
            }
        }
    }

    public static String xingEfupayWay = "";
    public static String xingEfuMoney = "";
    public static String xingEfuApiId = "";

    class XingefuReceived extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            XposedBridge.log("生成兴E付二维码...");
            try {
//				UINotifyListener
                xingEfuMoney = intent.getStringExtra("money");
                xingEfuApiId = intent.getStringExtra("apiorder_id");
                xingEfupayWay = intent.getStringExtra("type");
                String payWay = "1";
                if (xingEfupayWay.equals("wechat")) {
                    payWay = "1";
                } else if (xingEfupayWay.equals("alipay")) {
                    payWay = "2";
                } else if (xingEfupayWay.equals("qq")) {
                    payWay = "4";
                } else if (quanfutongPayWay.equals("unionpay")) {
                    payWay = "5";
                }

                Class<?> orderManagerCls = XposedHelpers.findClass("cn.swiftpass.enterprise.bussiness.logica.order.OrderManager", context.getClassLoader());
                Class<?> UINotifyListenerCls = XposedHelpers.findClass(" cn.swiftpass.enterprise.bussiness.logica.threading.UINotifyListener", context.getClassLoader());
                Object instance = XposedHelpers.callStaticMethod(orderManagerCls, "getInstance");
                Object UINotifyListener = XposedHelpers.newInstance(UINotifyListenerCls);
                XposedHelpers.callMethod(instance, "unifiedNativePay", xingEfuMoney, payWay, 0, null, null, UINotifyListener);

            } catch (Exception e) {
                PayHelperUtils.sendmsg(context, "StartLAkalaReceived 异常" + e.getMessage());
            }
        }
    }

    public static String newYSFpayWay = "";
    public static String newYSFMoney = "";
    public static String newYSFApiId = "";

    class NEWYSFReceived extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtil.printLog("云闪付收银台二维码...");
            try {
//				UINotifyListener
                newYSFMoney = intent.getStringExtra("money");
                newYSFApiId = intent.getStringExtra("apiorder_id");
                newYSFpayWay = intent.getStringExtra("type");
                String payWay = "1";
                if (newYSFpayWay.equals("wechat")) {
                    payWay = "1";
                } else if (newYSFpayWay.equals("alipay")) {
                    payWay = "2";
                } else if (newYSFpayWay.equals("qq")) {
                    payWay = "4";
                } else if (newYSFpayWay.equals("unionpay")) {
                    payWay = "5";
                }

                Class<?> orderManagerCls = XposedHelpers.findClass("cn.swiftpass.enterprise.bussiness.logica.order.OrderManager", context.getClassLoader());
                Class<?> UINotifyListenerCls = XposedHelpers.findClass(" cn.swiftpass.enterprise.bussiness.logica.threading.UINotifyListener", context.getClassLoader());
                Object instance = XposedHelpers.callStaticMethod(orderManagerCls, "getInstance");
                Object UINotifyListener = XposedHelpers.newInstance(UINotifyListenerCls);
                XposedHelpers.callMethod(instance, "unifiedNativePay", newYSFMoney, payWay, 0, null, null, UINotifyListener);

            } catch (Exception e) {
                PayHelperUtils.sendmsg(context, "StartYSFReceived 异常" + e.getMessage());
            }
        }
    }
}